<?php
class Wxcallbackapi
{
	private $_appid;
	private $_appsecret;
	private $_wx_type;
	private $CI;

	public function __construct($config = array())
    {
        $this->CI = &get_instance();
        if (!empty($config)){
            $this->_appid = $config['appid'];
            $this->_appsecret = $config['appsecret'];
            $this->_wx_type = $config['wxtype'];
            $this->CI->load->library("wxinterface/Wxinterface",array("appid"=>$this->_appid,"appsecret"=>$this->_appsecret,"wxtype"=>$this->_wx_type));
        } else {
            echo 'lack appid and appsecret';exit();
        }
    }

    //验证消息
	public function valid()
	{
		$echoStr = $_GET["echostr"];
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
	}

	//检查签名
	private function checkSignature()
	{
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];
		$token = "ChuLing";
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpStr);

		if($tmpStr == $signature){
			return true;
		}else{
			return false;
		}
	}

	//响应消息
	public function responseMsg()
	{
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		if (!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$RX_TYPE = trim($postObj->MsgType);

			switch ($RX_TYPE)
			{
				case "event":
					$result = $this->receiveEvent($postObj);
					break;
				case "text":
					$result = $this->receiveText($postObj);
					break;
				case "image":
					$result = $this->receiveImage($postObj);
					break;
				case "video":
					$result = $this->receiveVideo($postObj);
					break;
				case "shortvideo":
					$result = $this->receiveVideo($postObj);
					break;
				case "voice":
					$result = $this->receiveVoice($postObj);
					break;
				case "location":
					$result= $this->receiveLocation($postObj);
					break;
				case "link":
					$result= $this->receiveLink($postObj);
					break;
				default:
					$result="";
					break;
					 
			}
			return $result;
		}else {
			return  "";
		}
	}
	private function receiveImage($object)
	{
		$content="这张照片真漂亮！";
		$result=$this->transmitText($object, $content);
		return $result;
	}

	private function receiveVideo($object)
	{
		$content="这个视频看上去好像挺有趣的！";
		$result=$this->transmitText($object, $content);
		return $result;
	}

	//接收事件消息
	private function receiveEvent($object)
	{
		switch ($object->Event)
		{
			case "subscribe":
                $touser = $object->FromUserName;
                $tousername = $this->getUserNickName($touser);
			    switch ($this->_wx_type){
                    case 'ft_dy':
                        $content=$tousername."，终于等到你了，么么哒！欢迎关注《上海家庭时光社区服务中心》\n".
                            "我们是一家非盈利组织，旨在为0-18岁家庭提供科学育儿理念、亲子游戏活动指导、".
                            "亲子陪伴指导及亲子资讯等专业服务，解决您在家庭陪伴、家庭教育中的困惑。\n".
                            "觉得还不够？想要和抱有同样困惑的家长交流？想要让专家一对一支招？那么欢迎扫描《下方二维码》添加管理员为好友，".
                            "加入家庭时光社群";
                        $data = '{"touser":"'.$touser.'","msgtype":"text","text":{"content":"'.$content.'"}}';
                        $this->transmitCustomMsg($data);
                        $result=$this->transmitImage($object,'/home/nldou/webroot/api/img/FTSQ-admin-qrcode.jpg','FTSQ-admin-qrcode');
                        break;
                    default:
                        $result="";
                }
                //$result = $this->transmitVoice($object,'/home/nldou/webroot/api/testdata/testvoice.mp3','testvoice');
                /*$videoarr['videourl'] = '/home/nldou/webroot/api/testdata/testvideo.mp4';
				$videoarr['videoname'] = 'testvideo';
                $videoarr['Title'] = 'testvideo';
                $videoarr['Description'] = 'testvideo';
                $result = $this->transmitVideo($object,$videoarr);*/
                /*$musicarr['thumburl']='/home/nldou/webroot/api/testdata/testthumb.jpg';
                $musicarr['thumbname']='testthumb';
                $musicarr['Title']='testmusic';
                $musicarr['Description']='testmusic';
                $musicarr['MusicUrl']='http://api.nldou.com/testdata/testvoice.mp3';
                $musicarr['HQMusicUrl']='http://api.nldou.com/testdata/testvoice.mp3';
                $result=$this->transmitMusic($object,$musicarr);*/
                //$result="";
				break;
			default:
				$result="";
				break;
		}

		return $result;
	}

	//接收文本消息
	private function receiveText($object)
	{
		$object->Content =  trim($object->Content);
		$result=$this->transmitText($object,$object->Content);
		return $result;
	}
	
	private function receiveVoice($object){
		$result=$this->transmitService($object);
		return $result;
	}
	
	private function receiveLocation($object){
		$content="为什么发给我坐标呢？如果有什么需要，请点击菜单栏客服哦！";
		$result=$this->transmitText($object, $content);
		return $result;
	}
	
	private function receiveLink($object)
	{
		$content="为什么发给我链接呢？如果有什么需要，请点击菜单栏客服哦！";
		$result=$this->transmitText($object, $content);
		return $result;
	}
	//------------------------------------------------------------
	private function transmitText($object, $content)
	{
		$xml = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[text]]></MsgType>
		<Content><![CDATA[%s]]></Content>
		</xml>";
		$result = sprintf($xml, $object->FromUserName, $object->ToUserName, time(), $content);
		return $result;
	}

	private function transmitMusic($object, $musicarr)
	{
        $musicarr['ThumbMediaId'] = $this->getMediaid($musicarr['thumburl'],'thumb', $musicarr['thumbname']);
        log_message('error',$musicarr['ThumbMediaId']);
		$item = "<Music>
	    <Title><![CDATA[%s]]></Title>
	    <Description><![CDATA[%s]]></Description>
	    <MusicUrl><![CDATA[%s]]></MusicUrl>
	    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
	    <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
		</Music>";

		$item_xml = sprintf($item, $musicarr['Title'], $musicarr['Description'], $musicarr['MusicUrl'], $musicarr['HQMusicUrl'], $musicarr['ThumbMediaId']);

		$xml = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[music]]></MsgType>
		$item_xml
		</xml>";

		$result = sprintf($xml, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	private function transmitImage($object,$imgurl,$imgname)
	{
	    $imgid = $this->getMediaid($imgurl,'image',$imgname);
		$item="<Image><MediaId><![CDATA[%s]]></MediaId></Image>";
		$item_xml=sprintf($item,$imgid);
		$xml="<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[image]]></MsgType>
		$item_xml
		</xml>";
		$result = sprintf($xml, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}

	private function transmitVideo($object,$videoarr)
	{
	    $videoarr['MediaId'] = $this->getMediaid($videoarr['videourl'],'video',$videoarr['videoname']);

		$item="<Video><MediaId><![CDATA[%s]]></MediaId>
			<Title><![CDATA[%s]]></Title>
			<Description><![CDATA[%s]]></Description></Video>";
    	$item_xml=sprintf($item,$videoarr['MediaId'],$videoarr['Title'],$videoarr['Description']);
    	$xml="<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
    	<FromUserName><![CDATA[%s]]></FromUserName>
    	<CreateTime>%s</CreateTime>
    	<MsgType><![CDATA[video]]></MsgType>
    	$item_xml
    	</xml>";
    	$result = sprintf($xml, $object->FromUserName, $object->ToUserName, time());
    	return $result;
	}

	private function transmitVoice($object,$voiceurl,$voicename){
        $voiceid = $this->getMediaid($voiceurl,'voice',$voicename);

        $item="<Voice><MediaId><![CDATA[%s]]></MediaId></Voice>";
        $item_xml=sprintf($item,$voiceid);
        $xml="<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[voice]]></MsgType>
		$item_xml
		</xml>";
        $result = sprintf($xml, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

	//回复多客服消息
	private function transmitService($object)
	{
		$xml= "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[transfer_customer_service]]></MsgType>
		</xml>";
        $result = sprintf($xml, $object->FromUserName, $object->ToUserName, time());
        return $result;
	}

	private function transmitArticles($object,$data)
	{
		if(!isset($data) && empty($data)){
			return '';
	    }
		//导入图文数据
		/*$data=array(array(
				'title'      => '哇吖·城市探秘 | 上海滩杀人事件',
		'description'=> '100年前，法租界，预告的杀人案，档案馆，时空调查局（TBI），发迹前的黑帮大佬...是虚拟还是现实？是演绎',
		'picurl'     => 'https://mmbiz.qlogo.cn/mmbiz_jpg/Pu3ufsdDcY0O97jNtWW993WKiboPTjqIo9XpvR9kQxg51gH2aA54IhK9DmfX4oqYt1VPtEic47fxtSdFqFmvxxkA/0?wx_fmt=jpeg',
		'url'        => 'http://mp.weixin.qq.com/s?__biz=MzIyNzExNDcxOA==&mid=2656038215&idx=1&sn=d04f5ff0317a8b0d859bcce303a6bb5e&chksm=f3dd66f6c4aaefe0e86aafb6efe2a2c74adebf438b53287132290ac9a86d86f4064a77886e7b#rd'
		));*/
		$articles_count = count($data);
		//生成图文xml
		$item = "<item>
		<Title><![CDATA[%s]]></Title>
		<Description><![CDATA[%s]]></Description>
		<PicUrl><![CDATA[%s]]></PicUrl>
		<Url><![CDATA[%s]]></Url>
		</item>";
		$articles_xml = '';
    	foreach($data as $v){
    		$articles_xml .= sprintf($item,$v['title'],$v['description'],$v['picurl'],$v['url']);
    	}
    	//生成完整回复xml
		$xml = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[news]]></MsgType>
		<ArticleCount>%d</ArticleCount>
		<Articles>$articles_xml</Articles>
		</xml>";
		$result = sprintf($xml, $object->FromUserName, $object->ToUserName, time(),$articles_count);
		return $result;
	}

	private function transmitCustomMsg($data){
        $this->CI->wxinterface->send_custom_msg($data);
    }
	//获取临时素材（图片、声音、视频、缩率图）media_id
	private function getMediaid($mediaurl,$mediatype,$medianame){
        $res=$this->CI->wxinterface->upload_temp_media($mediaurl,$mediatype,$medianame);
        return $res;
    }
    private function getUserNickName($openid)
    {
        $res=$this->CI->wxinterface->getUserInfo($openid);
        return $res['nickname'];
    }
}